package com.trinh.utils.crypto.cryptors;

import com.trinh.utils.crypto.config.KeyConfig;
import com.trinh.utils.crypto.enu.Algorithm;
import com.trinh.utils.crypto.enu.CharFormater;
import com.trinh.utils.crypto.enu.Padding;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author: TrinhRae
 * @Package: com.trinh.utils.crypto.cryptors
 * @Project: generaltools
 * @Date: 2025/6/24 14:08
 */
public class HMACSignUtil {
    private KeyConfig keyConfig;
    private Algorithm algorithm;

    public HMACSignUtil(KeyConfig keyConfig, Algorithm algorithm, CharFormater keyCharFormater) {
        this.keyConfig = keyConfig;
        this.algorithm = algorithm;
        this.keyCharFormater = keyCharFormater;
    }

    private CharFormater keyCharFormater;


    /**
     * 使用指定算法进行 HMAC 签名
     *
     * @param data 待签名的数据
     * @return Base64 编码的签名字符串
     */
    public String sign(String data) throws Exception {
        String key = keyConfig.getPrivateKey();
        Mac mac = Mac.getInstance(algorithm.getSignAlgo());
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm.getSignAlgo());
        mac.init(secretKey);
        byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hmacBytes);
    }

    /**
     * 校验签名
     *
     * @param data      原始数据
     * @param signature 要校验的 Base64 签名字符串
     * @return 是否匹配
     */
    public boolean verify(String data, String signature) throws Exception {
        String expected = sign(data);
        return expected.equals(signature);
    }

}
